/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2012-11-20     Bernard    the first version
 * 2018-11-22     Jesven     add rt_hw_spin_lock
 *                           add rt_hw_spin_unlock
 *                           add smp ipi init
 */

#include <rthw.h>
#include <rtthread.h>

#include "board.h"

#include <mmu.h>

struct mem_desc platform_mem_desc[] = {
    {0x00000000, 0xFFFFFFFF, 0x00000000, DEVICE_MEM},
    {0x00000000, 0x000FFFFF, 0x00000000, NORMAL_MEM},
    {0x42000000, 0x47FFFFFF, 0x42000000, NORMAL_MEM},
};

const rt_uint32_t platform_mem_desc_size = sizeof(platform_mem_desc)/sizeof(platform_mem_desc[0]);

#define SYS_CTRL                        __REG32(REALVIEW_SCTL_BASE)

extern void rt_hw_ipi_handler_install(int ipi_vector, rt_isr_handler_t ipi_isr_handler);

void idle_wfi(void)
{
    asm volatile ("wfi");
}
#include "drv_watchdog.h"




#define TIMER_BASE             0x02050000
#define TMR_IRQ_EN_REG         0x00
#define TMR_IRQ_STA_REG        0x04
#define TMR0_CTRL_REG          0x10
#define TMR0_INTV_VALUE_REG    0x14
#define TMR0_CUR_VALUE_REG     0x18


void clock_irq(int vector, void *param)
{
    (void) param;
     /* 中断使用说明：先清源头中断，在清GIC中断, */
    volatile unsigned int * p_temp = (unsigned int *) (TIMER_BASE + TMR_IRQ_STA_REG);  //临时指针

    rt_interrupt_enter();

    // rt_kprintf("%d", vector);

    *p_temp |= (*p_temp & 0x01);

    rt_hw_interrupt_ack(vector);

    rt_tick_increase();

    rt_interrupt_leave();
}

void set_os_clock(void)
{
    volatile unsigned int * p_temp;  //临时指针

    /* 打开定时器0的中断 */
    p_temp = (unsigned int *) (TIMER_BASE + TMR_IRQ_EN_REG);
    *p_temp |= 0x01;

    /*循环计数 24M时钟源  2分频  自动重装载值 不启动计数器*/
    p_temp = (unsigned int *) (TIMER_BASE + TMR0_CTRL_REG);
    *p_temp &= 0x00;
    *p_temp |= 0x16;

    /* 定时器间隔 0  */
    p_temp = (unsigned int *) (TIMER_BASE + TMR0_INTV_VALUE_REG);
    *p_temp = 1000 * 12;

    /* 定时器计数个数 */
    p_temp = (unsigned int *) (TIMER_BASE + TMR0_CUR_VALUE_REG);
    *p_temp = 1000 * 12;

    /* 打开定时器，开始工作 */
    p_temp = (unsigned int *) (TIMER_BASE + TMR0_CTRL_REG);
    *p_temp |= 0x01;
    /* 使能中断 */
    rt_hw_interrupt_install(T113_IRQ_TIMER0, clock_irq, RT_NULL, "TIMER0");
    rt_hw_interrupt_umask(T113_IRQ_TIMER0);
}
/**
 * This function will initialize beaglebone board
 */
void rt_hw_board_init(void)
{

    rt_hw_interrupt_init();
    /* initialize system heap */
    rt_system_heap_init(HEAP_BEGIN, HEAP_END);
    rt_components_board_init();
    rt_console_set_device(RT_CONSOLE_DEVICE_NAME);
    sunxi_clk_init();//工作1.2G频率
    /* 设置时钟 */
    set_os_clock();
    rt_thread_idle_sethook(idle_wfi);

#ifdef RT_USING_SMP
    /* install IPI handle */
    rt_hw_ipi_handler_install(RT_SCHEDULE_IPI, rt_scheduler_ipi_handler);
#endif
}

